/**
 * ReportGear(2011)
 */
package com.reportgear.report.print;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.reportgear.core.util.UnitUtils;
import com.reportgear.report.core.model.util.BaseUtils;
import com.reportgear.report.model.ReportModel;
import com.reportgear.report.setting.PaperSetting;
import com.reportgear.report.setting.ReportSettings;
import com.reportgear.report.view.grid.util.GraphHelper;

/**
 * 打印类
 * 
 * @version 1.0 2011-4-19
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class Printer {
	private static final Logger logger = LoggerFactory.getLogger(Printer.class.getName());

	public void print(Iterator<ReportPage> iterator, ReportModel model) {
		PageFormat pageFormat = new PageFormat();

		ReportSettings reportSettings = model.getReportSettings();
		PaperSetting paperSetting = reportSettings.getPaperSetting();
		PaperSize paperSize = paperSetting.getPaperSize();
		Paper paper = pageFormat.getPaper();

		double ptWidth = UnitUtils.inch2pt(paperSize.getWidth());
		double ptHeight = UnitUtils.inch2pt(paperSize.getHeight());

		paper.setSize(ptWidth, ptHeight);

		paper.setImageableArea(0, 0, ptWidth, ptHeight);
		pageFormat.setPaper(paper);

		pageFormat.setOrientation(paperSetting.getOrientation());
		try {
			this.print(iterator, pageFormat);
		} catch (PrinterException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 报表打印
	 * 
	 * @param pages
	 *            页面列表
	 * @param format
	 *            格式
	 * @throws PrinterException
	 *             打印异常
	 */
	public void print(Iterator<ReportPage> pages, PageFormat format) throws PrinterException {
		PrintService service = null;
		if (service == null) {
			service = PrintServiceLookup.lookupDefaultPrintService();
		}
		PrinterJob job = PrinterJob.getPrinterJob();
		try {
			job.setPrintService(service);
		} catch (PrinterException ex) {
			logger.warn(ex.getMessage());
		}

		Book book = new Book();

		while (pages.hasNext()) {
			ReportPage object = (ReportPage) pages.next();
			book.append(object, format);
		}
		job.setPageable(book);
		job.validatePage(format);

		if (!job.printDialog()) {
			return;
		}

		try {
			job.print();
		} catch (PrinterException ex) {
			logger.warn(ex.getMessage());
		}
	}
}
